/*
 *Create By：Z.B
 *@DATE 2019/3/18 17:10
 *@EMAIL: 2545375@qq.com
 */
'use strict';

const Service = require('egg').Service;

class UserService extends Service {
  async index(payload){

  }

  async create(payload){
    const {ctx,service } = this;
    // const role = await service.role.show(payload.role);
    // if(!role){
    //   ctx.throw(404,'Role is not found');
    // }
    payload.password = await ctx.genHash(payload.password);
    return ctx.model.User.create(payload);
  }

  async destroy(_id){
    const {ctx, service } = this;
    const user = await service.user.find(_id);
    if(!user){
      ctx.throw(404,'user not found');
    }
    return ctx.model.User.findByIdAndRemove(_id);
  }

  async update(_id, payload){
    const {ctx, service} = this;
    const user = await service.user.find(_id);
    if(!user){
      ctx.throw(404,'user not found');
    }
    return ctx.model.User.findByIdAndUpdate(_id, payload);
  }

  async show(_id){
    const user = await this.ctx.service.user.find(_id);
    if(!user){
      ctx.throw(404,'user not found');
    }
    return this.ctx.model.User.findById(_id).populate('role');
  }

  async index(payload){

  }

  async removes(payload){
    return this.ctx.model.User.remove({_id:{$in:payload}});
  }

  //Commons
  async findByMobile(mobile){
    return this.ctx.model.User.findOne({mobile:mobile});
  }

  async findByAccount(account){
    return this.ctx.model.User.findOne({account: account});
  }

  async find(id){
    return this.ctx.model.User.findById(id);
  }

  async findByIdAndUpdate(id,values){
    return this.ctx.model.User.findByIdAndUpdate(id, values);
  }
}

module.exports = UserService;